package com.shaoshaohuo.app.ui;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CheckPayPwdEntity;
import com.shaoshaohuo.app.entity.SupportWithdrawWay;
import com.shaoshaohuo.app.entity.SupportWithdrawWayEntity;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper.Field;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.adapter.WithdrawWayAdapter;
import com.shaoshaohuo.app.view.TopbarView;

/**
 * 
 * @author cao
 *
 */
public class WithdrawActivity extends BaseActivity implements OnClickListener {

	private TopbarView mTopbarView;

	private TextView mLeftMoneyText;

	private View mMoneyLayout;
	private View mCardNameLayout;
	private View mCardNumberLayout;
	private View mCardTypeLayout;
	private View mNumLayout;

	private EditText mMoneyEidt;
	private EditText mCardNameEidt;
	private EditText mCardNumberEidt;
	private TextView mCardTypeText;
	private EditText mNumEidt;
	private Button mAuthcodeButton;
	private EditText mAuthcodeNum;
	private Button mNextButton;

	private String id, account, realname, money, cardNum ,authcode;

	protected List<SupportWithdrawWay> supportWayList;

	private AlertDialog cardTypeDialog;

	protected SupportWithdrawWay selectWithdrawWay;

	private String freetotal;
	private boolean isHaveNum;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdraw);

		initData();
		initView();
		setUpView();
		getSupportWithdraw();
	}

	private void initData() {
		freetotal = getIntent().getStringExtra(ExtraName.freetotal);
		String num = SharedPreferencesHelper.getString(Field.USER_CARD_NUM, "");
		if (!TextUtils.isEmpty(num)) {
			isHaveNum = true;
		}else{
			isHaveNum = false;
		}
	}

	private void getSupportWithdraw() {
		RequestService.getInstance().supportWithdraw(this, SupportWithdrawWayEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					SupportWithdrawWayEntity entity = (SupportWithdrawWayEntity) resultData;
					supportWayList = entity.getData().getList();
				} else {
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
			}
		});
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mLeftMoneyText = (TextView) this.findViewById(R.id.textview_left_money);

		mMoneyLayout = this.findViewById(R.id.layout_money);
		mCardNameLayout = this.findViewById(R.id.layout_card_name);
		mCardNumberLayout = this.findViewById(R.id.layout_card_number);
		mCardTypeLayout = this.findViewById(R.id.layout_card_type);
		mNumLayout = this.findViewById(R.id.layout_num);

		mMoneyEidt = (EditText) this.findViewById(R.id.edittext_money);
		mCardNameEidt = (EditText) this.findViewById(R.id.edittext_card_name);
		mCardNumberEidt = (EditText) this.findViewById(R.id.edittext_card_number);
		mCardTypeText = (TextView) this.findViewById(R.id.textview_card_type);
		mNumEidt = (EditText) this.findViewById(R.id.textview_num);
		mAuthcodeNum = (EditText) this.findViewById(R.id.edittext_authcode);

		mAuthcodeButton = (Button) this.findViewById(R.id.button_authcode);
		mNextButton = (Button) this.findViewById(R.id.button_next);
	}

	private void setUpView() {
		mTopbarView.setCenterText("提现");
		mTopbarView.setLeftView(true, true);

		mLeftMoneyText.setText("可提现金额:￥" + freetotal);

		if (isHaveNum) {
			mNumLayout.setVisibility(View.GONE);
		}
		mCardTypeLayout.setOnClickListener(this);
		mNextButton.setOnClickListener(this);
		mAuthcodeButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_card_type:
			selectCardType();
			break;
		case R.id.button_authcode:
			getAuthcode();
			break;
			
		case R.id.button_next:

			money = mMoneyEidt.getText().toString().trim();
			realname = mCardNameEidt.getText().toString().trim();
			account = mCardNumberEidt.getText().toString().trim();
			if (selectWithdrawWay == null) {
				showToast("请选择提现方式");
				return;
			}
			id = selectWithdrawWay.getId();
			cardNum = mNumEidt.getText().toString().trim();
			authcode  = mAuthcodeNum.getText().toString().trim();

			if (TextUtils.isEmpty(money)) {
				showToast("请输入提现金额");
				return;
			}

			if (TextUtils.isEmpty(realname)) {
				showToast("请输入持卡人");
				return;
			}

			if (TextUtils.isEmpty(account)) {
				showToast("请输入卡号");
				return;
			}

			if (Double.parseDouble(money) < 10) {
				showToast("提现金额应大于10元");
				return;
			}
			if (Double.parseDouble(money) > 50000) {
				showToast("单笔提现金额不能超过5万");
				return;
			}
			if (Double.parseDouble(money) > Double.parseDouble(freetotal)) {
				showToast("可提现金额不足");
				return;
			}
			if (!isHaveNum && TextUtils.isEmpty(cardNum)) {
				showToast("请输入身份证号码");
				return;
			}
			if(TextUtils.isEmpty(authcode)){
				showToast("请输入验证码");
				return;
			}
			
			checkPayPwd();
			
			break;
		}
		
	}

	private void showPwdDialog(CheckPayPwdEntity entity) {
		if ("1".equals(entity.getData().getIsset())) {
			// PayDialog dialog = new PayDialog(this);
			// dialog.setOnBtClickListener(new OnBtClickListener() {
			//
			// @Override
			// public void onPayClick(String pwd) {
			withdraw();
			// }
			// });
			// dialog.show();
		} else {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("未设置支付密码,请先设置支付密码");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(WithdrawActivity.this, PayManageActivity.class);
					startActivity(intent);
				}
			});
			builder.create().show();

		}
	}

	private void checkPayPwd() {
		startLoadingDialog();
		RequestService.getInstance().checkPayPwd(this, CheckPayPwdEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					CheckPayPwdEntity entity = (CheckPayPwdEntity) resultData;
					showPwdDialog(entity);
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	protected void selectCardType() {

		if (supportWayList == null || supportWayList.isEmpty()) {
			showToast("暂无支持的支付方式");
			return;
		}

		if (cardTypeDialog != null && cardTypeDialog.isShowing()) {
			return;
		}
		if (cardTypeDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			WithdrawWayAdapter<SupportWithdrawWay> adapter = new WithdrawWayAdapter<SupportWithdrawWay>(this,
					supportWayList, false);
			builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					selectWithdrawWay = supportWayList.get(which);
					mCardTypeText.setText(selectWithdrawWay.getTitle());
				}
			});
			cardTypeDialog = builder.create();
			cardTypeDialog.setTitle("选择卡类型");

		}
		cardTypeDialog.show();
	}

	private void withdraw() {
		startLoadingDialog();
		RequestService.getInstance().withdraw(this, id, account, realname, cardNum, money,authcode, BaseEntity.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							showToast("提现申请提交成功");
							// 跳转到提现申请成功页面
							SharedPreferencesHelper.setString(Field.SHOW_BANK_NAME,
									selectWithdrawWay.getTitle());
							SharedPreferencesHelper.setString(Field.SHOW_BANK_ACCOUNT, account);
							SharedPreferencesHelper.setString(Field.SHOW_BANK_MONEY, money);
							SharedPreferencesHelper.setString(Field.SHOW_BANK_ACCOUNT_NAME, realname);
							startActivity(new Intent(getApplicationContext(), WithDrawEndingActivity.class));
							finish();
						} else {
							showToast(resultData.getMsg());
						}
					}

					@Override
					public void onFailed(int requestCode, Exception error, String msg) {
						dismissLoadingDialog();
						showToast(R.string.please_check_network);
					}
				});
	}
	
	private void getAuthcode() {

		startLoadingDialog();
		RequestService.getInstance().sendPaySms(this, BaseEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					mAuthcodeButton.setEnabled(false);
					mHandler.removeMessages(0);
					mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1 * 1000);
					showToast("验证码已发送");
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	private static final int DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME = 60;
	private int mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				--mUpdateCount;
				if (mUpdateCount > 0) {
					mAuthcodeButton.setText(String.format("重新发送(%d)", mUpdateCount));
					sendMessageDelayed(obtainMessage(0), 1 * 1000);
					mAuthcodeButton.setEnabled(false);
				} else {
					mAuthcodeButton.setText("重新发送");
					mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
					mAuthcodeButton.setEnabled(true);
				}
			}
		}
	};

}
